package com.zh.job.once;

import cn.hutool.core.util.StrUtil;
import com.zh.config.RedisConfig;
import com.zh.config.RedisKeyConfig;
import com.zh.utils.RSAUtil;
import com.zh.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * 初始化密码对
 */
@Component
@Slf4j
public class RSASetUp implements CommandLineRunner {

    private final RedisUtil redisUtil;

    public RSASetUp(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public void run(String... args) {
        //1.先从redis找
        String publicKey = RedisKeyConfig.PUBLICKEY;
        String privateKey = RedisKeyConfig.PRAVIEKEY;
        String publicKeyStr = redisUtil.get(publicKey);
        String privateKeyStr = redisUtil.get(privateKey);
        if (StrUtil.isNotEmpty(publicKeyStr) && StrUtil.isNotBlank(privateKeyStr)) {
            RSAUtil.keyPairMap.put(RSAUtil.publicKeyName, publicKeyStr);
            RSAUtil.keyPairMap.put(RSAUtil.privateKeyName, privateKeyStr);
            log.info("成功从redis中获取到密钥对");
            return;
        }
        //2.找不到再生成
        RSAUtil.generateKey();
        publicKeyStr = RSAUtil.getPublicKey();
        privateKeyStr = RSAUtil.getPrivateKey();
        //3.存回redis,约定30天
        redisUtil.set(publicKey, publicKeyStr, 30, TimeUnit.DAYS);
        redisUtil.set(privateKey, privateKeyStr, 30, TimeUnit.DAYS);
        log.info("未找到密钥对,已重新生成并存入redis:publicKey:[{}],privateKey:[{}]", RedisKeyConfig.PUBLICKEY, RedisKeyConfig.PRAVIEKEY);
    }
}
